package com.jinke.api.modules.api.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinke.api.common.api.CommonResult;
import com.jinke.api.modules.app.enums.OrderStatus;
import com.jinke.api.modules.app.model.Order;
import com.jinke.api.modules.app.model.OrderParcel;
import com.jinke.api.modules.app.service.OrderParcelService;
import com.jinke.api.modules.app.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * TrackingApi
 *
 * @author huang
 * @data 2024-06-05
 */
@Slf4j
@RestController
@RequestMapping("/track/api")
public class TrackApiController {
    @Resource
    private OrderParcelService orderParcelService;
    @Resource
    private OrderService orderService;
    private final static String testBody = "{\n" +
            "  \"event\": \"TRACKING_UPDATED\",\n" +
            "  \"data\": {\n" +
            "    \"number\": \"2736863216391\",\n" +
            "    \"carrier\": 3011,\n" +
            "    \"param\": \"518000\",\n" +
            "    \"tag\": \"myID\",\n" +
            "    \"track_info\": {\n" +
            "      \"shipping_info\": {\n" +
            "        \"shipper_address\": {\n" +
            "          \"country\": \"CN\",\n" +
            "          \"state\": \"GD\",\n" +
            "          \"city\": \"SHENZHEN\",\n" +
            "          \"street\": \"HARTFORD CT DISTRIBUTION CENTER\",\n" +
            "          \"postal_code\": \"518000\",\n" +
            "          \"coordinates\": {\n" +
            "            \"longitude\": \"114.085947\",\n" +
            "            \"latitude\": \"22.547\"\n" +
            "          }\n" +
            "        },\n" +
            "        \"recipient_address\": {\n" +
            "          \"country\": \"AF\",\n" +
            "          \"state\": null,\n" +
            "          \"city\": \"KABUL\",\n" +
            "          \"street\": null,\n" +
            "          \"postal_code\": null,\n" +
            "          \"coordinates\": {\n" +
            "            \"longitude\": null,\n" +
            "            \"latitude\": null\n" +
            "          }\n" +
            "        }\n" +
            "      },\n" +
            "      \"latest_status\": {\n" +
            "        \"status\": \"InfoReceived\",\n" +
            "        \"sub_status\": \"InfoReceived\",\n" +
            "        \"sub_status_descr\": null\n" +
            "      },\n" +
            "      \"latest_event\": {\n" +
            "        \"time_iso\": \"2022-05-23T22:22:00+08:00\",\n" +
            "        \"time_utc\": \"2022-05-23T14:22:00Z\",\n" +
            "        \"description\": \"Shipment information sent to FedEx\",\n" +
            "        \"description_translation\": {\n" +
            "            \"lang\": \"en\",\n" +
            "            \"description\": \"Shipment information sent to FedEx\"\n" +
            "        },\n" +
            "        \"location\": \"NJ\",\n" +
            "        \"stage\": \"InfoReceived\",\n" +
            "        \"address\": {\n" +
            "          \"country\": \"US\",\n" +
            "          \"state\": \"NJ\",\n" +
            "          \"city\": \"MARLTON\",\n" +
            "          \"street\": null,\n" +
            "          \"postal_code\": \"08053\",\n" +
            "          \"coordinates\": {\n" +
            "            \"longitude\": null,\n" +
            "            \"latitude\": null\n" +
            "          }\n" +
            "        }\n" +
            "      },\n" +
            "      \"time_metrics\": {\n" +
            "        \"days_after_order\": 7,\n" +
            "        \"days_of_transit\": 7,\n" +
            "        \"days_of_transit_done\": 7,\n" +
            "        \"days_after_last_update\": 57,\n" +
            "        \"estimated_delivery_date\": {\n" +
            "          \"source\":\"Official\",\n" +
            "          \"from\": \"2022-03-02T18:43:24-06:00\", \n" +
            "          \"to\": \"2022-03-03T19:43:24-06:00\" \n" +
            "        }\n" +
            "      },\n" +
            "      \"milestone\": [\n" +
            "        {\n" +
            "          \"key_stage\": \"InfoReceived\",\n" +
            "          \"time_iso\": \"2022-04-25T22:22:47-05:00\",\n" +
            "          \"time_utc\": \"2022-04-26T03:22:47Z\"\n" +
            "        },\n" +
            "        {\n" +
            "          \"key_stage\": \"PickedUp\",\n" +
            "          \"time_iso\": \"2022-04-25T16:22:00+08:00\",\n" +
            "          \"time_utc\": \"2022-04-25T08:22:00Z\"\n" +
            "        },\n" +
            "        {\n" +
            "          \"key_stage\": \"Departure\",\n" +
            "          \"time_iso\": \"2022-05-19T21:40:00+08:00\",\n" +
            "          \"time_utc\": \"2022-05-19T13:40:00Z\"\n" +
            "        },\n" +
            "        {\n" +
            "          \"key_stage\": \"Arrival\",\n" +
            "          \"time_iso\": null,\n" +
            "          \"time_utc\": null\n" +
            "        },\n" +
            "        {\n" +
            "          \"key_stage\": \"AvailableForPickup\",\n" +
            "          \"time_iso\": null,\n" +
            "          \"time_utc\": null\n" +
            "        },\n" +
            "        {\n" +
            "          \"key_stage\": \"OutForDelivery\",\n" +
            "          \"time_iso\": null,\n" +
            "          \"time_utc\": null\n" +
            "        },\n" +
            "        {\n" +
            "          \"key_stage\": \"Delivered\",\n" +
            "          \"time_iso\": null,\n" +
            "          \"time_utc\": null\n" +
            "        },\n" +
            "        {\n" +
            "          \"key_stage\": \"Returning\",\n" +
            "          \"time_iso\": null,\n" +
            "          \"time_utc\": null\n" +
            "        },\n" +
            "        {\n" +
            "          \"key_stage\": \"Returned\",\n" +
            "          \"time_iso\": null,\n" +
            "          \"time_utc\": null\n" +
            "        }\n" +
            "      ],\n" +
            "      \"misc_info\": {\n" +
            "        \"risk_factor\": 0,\n" +
            "        \"service_type\": \"FedEx International Priority\",\n" +
            "        \"weight_raw\": \"1.1 KG\",\n" +
            "        \"weight_kg\": \"1.1\",\n" +
            "        \"pieces\": \"1\",\n" +
            "        \"dimensions\": \"22*20*16 CM\",\n" +
            "        \"customer_number\": \"2459642000~270434455123~FX\",\n" +
            "        \"reference_number\": null,\n" +
            "        \"local_number\": \"270434455123\",\n" +
            "        \"local_provider\": \"Fedex\",\n" +
            "        \"local_key\": 100003\n" +
            "      },\n" +
            "      \"tracking\": {\n" +
            "        \"providers_hash\": 2067301750,\n" +
            "        \"providers\": [\n" +
            "          {\n" +
            "            \"provider\": {\n" +
            "              \"key\": 3011,\n" +
            "              \"name\": \"China Post\",\n" +
            "              \"alias\": \"China Post\",\n" +
            "              \"tel\": null,\n" +
            "              \"homepage\": \"http://www.17track.net\",\n" +
            "              \"country\": \"CN\"\n" +
            "            },\n" +
            "            \"service_type\": \"International Priority\",\n" +
            "            \"latest_sync_status\": \"Success\",\n" +
            "            \"latest_sync_time\": \"2022-06-09T05:46:31Z\",\n" +
            "            \"events_hash\": -227928244,\n" +
            "            \"events\": [\n" +
            "              {\n" +
            "                \"time_iso\": \"2022-04-29T09:19:00-08:00\",\n" +
            "                \"time_utc\": \"2022-04-29T17:19:00Z\",\n" +
            "                \"description\": \"At local FedEx facility\",\n" +
            "                \"description_translation\": {\n" +
            "                    \"lang\": \"en\",\n" +
            "                    \"description\": \"At local FedEx facility\"\n" +
            "                },\n" +
            "                \"location\": \"ANCHORAGE, AK, US\",\n" +
            "                \"stage\": \"InfoReceived\",\n" +
            "                \"address\": {\n" +
            "                  \"country\": \"US\",\n" +
            "                  \"state\": \"AK\",\n" +
            "                  \"city\": \"ANCHORAGE\",\n" +
            "                  \"street\": null,\n" +
            "                  \"postal_code\": \"99502\",\n" +
            "                  \"coordinates\": {\n" +
            "                    \"longitude\": \"35.86166\",\n" +
            "                    \"latitude\": \"104.195397\"\n" +
            "                  }\n" +
            "                }\n" +
            "              }\n" +
            "            ]\n" +
            "          }\n" +
            "        ]\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";

    @PostMapping("/notify")
    public CommonResult notify(@RequestBody String body) {
        String number = "";
        String status = "";
        try {
            JSONObject jsonBody = JSON.parseObject(body);
            JSONObject jsonData = jsonBody.getJSONObject("data");
            //运单号
            number = jsonData.getString("number");
            log.info("TrackApi回调信息--------------->{},{}", number, body);
            //订单状态

            status = jsonData.getJSONObject("track_info").getJSONObject("latest_status").getString("sub_status");
        } catch (Exception e) {
            log.info("TrackApi解析异常--------->" + e.getMessage());
            return CommonResult.failed();
        }
        //查询对应的包裹信息
        OrderParcel orderParcel = orderParcelService.lambdaQuery().eq(OrderParcel::getTrackingNumber, number).one();
        if (ObjectUtil.isNotEmpty(orderParcel)) {
            Order order = orderService.lambdaQuery().eq(Order::getId, orderParcel.getOrderId()).one();
            if (ObjectUtil.isNotEmpty(order)) {
                //查询修改对应的订单信息
                //只有当订单处于1 待运输 2 运输中 异常一般是运输过久后面可能也会签收 的进行操作
                Integer nowStatus = order.getStatus();
                if (nowStatus == OrderStatus.RECENT.getValue()||nowStatus == OrderStatus.IN_TRANSIT.getValue()
                        ||nowStatus == OrderStatus.FAILURE.getValue()
                ) {
                    //新状态
                    Integer orderStatus = null;
                    if (status.contains("Delivered_Other")) {
                        //如果是已经申请取消但面单还是用了签收的不改变状态

                        //成功签收
                        orderStatus = OrderStatus.DELIVERED.getValue();
                    } else if (status.contains("Exception")) {
                        //失败
                        orderStatus = OrderStatus.FAILURE.getValue();
                    } else if (status.contains("InTransit")) {
                        //运输中
                        orderStatus = OrderStatus.IN_TRANSIT.getValue();
                    } else if (status.contains("InfoReceived")) {
                        //预上网
                        orderStatus = OrderStatus.InfoReceived.getValue();
                    }

                    log.info(number + "当前状态" + nowStatus + "-回传状态:" + status);

                    if (orderStatus != null) {

                        orderService.lambdaUpdate().eq(Order::getId, order.getId()).eq(Order::getStatus, nowStatus).set(Order::getStatus, orderStatus).update();
                    }
                }
            }
        }
        return CommonResult.success();
    }

}
